package com.example.jopewars;

import java.awt.GridLayout;

import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.TitledBorder;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.util.Enumeration;

public class LocationPanel extends JPanel implements GameStateChangedListener {

	private static final long serialVersionUID = 1L;

	private final ButtonGroup buttonGroup = new ButtonGroup();

	private GameEngine game;

	public LocationPanel() {
		game = GameEngine.getInstance();
		initialize();
	}

	private void initialize() {
		setBorder(new TitledBorder(null, "Location", TitledBorder.LEADING,
				TitledBorder.TOP, null, null));
		setLayout(new GridLayout(3, 3, 0, 0));

		for (Location loc : Location.getLocations()) {
			String name = loc.getName();
			JRadioButton btn = new JRadioButton(name);
			btn.addItemListener(new ItemListener() {
				public void itemStateChanged(ItemEvent arg0) {
					handleItemStateChanged(arg0);
				}
			});
			btn.setEnabled(false);
			buttonGroup.add(btn);
			add(btn);
		}
	}

	private void handleItemStateChanged(ItemEvent event) {
		JRadioButton btn = (JRadioButton) event.getItem();
		if (btn.isSelected()) {
			Location newLoc = Location.getLocation(btn.getText());
			game.nextTurn(newLoc);
		}
	}

	@Override
	public void gameStateChanged() {

	}

	public void startGame() {
		Enumeration<AbstractButton> btns = buttonGroup.getElements();
		while (btns.hasMoreElements()) {
			AbstractButton btn = btns.nextElement();
			btn.setEnabled(true);
		}
	}
}
